﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace CNdotnet.Ezsocio.PluginFramework
{
    public static class PlugInManager
    {
        #region Public Methods

        /// <summary>
        /// Setups the Plug-In host
        /// </summary>
        public static void Setup()
        {
            IPlugInHost host = PlugInHostFactory.Create();
            host.Load();
        }

        public static void Teardown()
        {
            IPlugInHost host = CurrentHost;
            host.UnLoad();
            PersistHost(null);
        }

        public static List<ManagedPlugin> GetPlugInList()
        {
            var result = from p in CurrentHost.Extensions
                         select p.Value.Current;

            return result.ToList<ManagedPlugin>();
        }

        public static IPlugInContext GetPlugIn(string key)
        {
            if (!CurrentHost.Extensions.ContainsKey(key))
            {
                throw new Exception("The key of {0} does not exist!");
            }

            return CurrentHost.Extensions[key];
        }

        #endregion

        #region Private Methods

        private static void OnLoadComplete(object sender, EventArgs e)
        {
            IPlugInHost host = sender as IPlugInHost;
            PersistHost(host);
        }

        private static void PersistHost(IPlugInHost host)
        {
            CurrentHttpContext.Application["PlugIns"] = host;
        }

        #endregion

        #region Properties

        public static IPlugInHost CurrentHost
        {
            get
            {
                if (CurrentHttpContext.Application["PlugIns"] == null)
                {
                    throw new Exception("The current Plug-In host is null");
                }

                IPlugInHost host = CurrentHttpContext.Application["PlugIns"] as IPlugInHost;
                return host;
            }
        }

        public static HttpContext CurrentHttpContext
        {
            get 
            {
                HttpContext httpContext = HttpContext.Current;
                if (httpContext == null)
                {
                    throw new Exception("The current HttpContext is null");
                }

                return httpContext;
            }
        }

        #endregion
    }
}
